package ncme.auto.framework.core.services.Impl;

import ncme.auto.framework.core.services.AspectPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Primary
public class AspectPermissionServiceImpl implements AspectPermissionService {

    //service注入需要
    @Autowired
    protected ApplicationContext applicationContext;

    public Integer getUserIdFromRequest(HttpServletRequest request) {
        String userId = request.getAttribute("userId").toString();
        return Integer.parseInt(userId);
    }


    public String getUserNameFromRequest(HttpServletRequest request) {
        return request.getAttribute("userName").toString();
    }


    public List<Integer> getUserPerms(Integer userId, Integer permissionCode) {
        Map<String, AspectPermissionServiceImpl> beansOfType = applicationContext.getBeansOfType(AspectPermissionServiceImpl.class);
        if (beansOfType.size() != 1) {
            for (String beanKey : beansOfType.keySet()) {
                if (!beanKey.equals("aspectPermissionServiceImpl")) {
                    AspectPermissionServiceImpl aspectPermissionService = beansOfType.get(beanKey);
                    return aspectPermissionService.getUserPerms(userId, permissionCode);
                }
            }
        }
        return new ArrayList<>();
    }


}
